package com.tma.demolocalservice;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener {
    static final String TAG = "MainActivity";
    private TextView mStatusTextView;
    private Button mStartButton;
    private Button mStopButton;
    private Handler mHandler;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mHandler = new IncomingHandler(this);
        mStartButton = (Button) findViewById(R.id.btn_start_service);
        mStopButton = (Button) findViewById(R.id.btn_stop_service);
        mStatusTextView = (TextView) findViewById(R.id.tv_status);

        mStartButton.setOnClickListener(this);
        mStopButton.setOnClickListener(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.btn_start_service:
            doStartService();
            break;
        case R.id.btn_stop_service:
            doStopService();
            break;
        default:
            break;
        }
    }

    private void updateStatus(String status) {
        mStatusTextView.setText(status);
    }

    private void doStartService() {
        Intent intent = new Intent(this, MyLocalService.class);

        // send the Messenger back to service so that 
        // the service can communicate back to our activity
        Messenger messenger = new Messenger(mHandler);
        intent.putExtra(I.KEY_MESSENGER, messenger);

        startService(intent);
    }

    private void doStopService() {
        Intent intent = new Intent(this, MyLocalService.class);
        stopService(intent);
    }

    /**
     * Handler of incoming messages from service.
     */
    static class IncomingHandler extends Handler {
        private MainActivity mActivity;
        public IncomingHandler(MainActivity activity) {
            mActivity = activity;
        }
        @Override
        public void handleMessage(Message msg) {
            Bundle b = msg.getData();
            String status = b.getString(I.KEY_STATUS);
            mActivity.updateStatus(status);
        }
    }
}
